package security.filters;

import framework.config.SecurityConfig;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import security.utils.SecurityAuthUtil;
import security.utils.SecurityTokenUtil;
import security.utils.TokenDetail;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 获取上级传送的Auth Identity
 */
@Slf4j
public class AuthIdentityServletFilter implements Filter {

    @Getter
    private SecurityConfig securityConfig;

    //
    public final String authIdentityHeaderName;

    public AuthIdentityServletFilter(SecurityConfig securityConfig) {
        this.securityConfig = securityConfig;
        //
        String identityHeader = securityConfig.getAuthIdentityHeader();
        if (!StringUtils.hasText(identityHeader)) {
            throw new IllegalArgumentException("Not configuration sys.security.auth_identity_header");
        }
        this.authIdentityHeaderName = identityHeader;
    }

    protected AuthenticationData parseAuthIdentity(HttpServletRequest request) {
        String identity = request.getHeader(authIdentityHeaderName);
        if (StringUtils.hasText(identity)) {
            try {
                return AuthenticationData.fromBase64(identity);
            } catch (Exception exception) {
                log.error("parse auth identity error " + exception.getMessage(), exception);
                return null;
            }
        }
        return null;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 配置了网关授权头
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //
        AuthenticationData data = this.parseAuthIdentity(request);
        if (data == null) {
            data = new AuthenticationData(0L, "", 0L);
        }

        //
        if (data.getId() == 0) {
            // enable debug
            if (getSecurityConfig().getDebugAccountId() != null) {
                data = new AuthenticationData(
                        getSecurityConfig().getDebugAccountId()
                        , "{DEBUG}"
                        , 0L);
            }
        }

        // token get
        TokenDetail tokenDetail = SecurityTokenUtil.getRequestToken(request, getSecurityConfig());
        if (tokenDetail == null) {
            response.sendError(500, "illegal access, gateway and application authentication failed");
            return;
        }

        // 将获取到的数据填充到安全组件
        SecurityAuthUtil.authorized(data);
        //
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
